<script setup>
import {onMounted, ref} from "vue";
import {useUserStore} from "../store/user.js";
import {_list, _add, _remove, _enable, _unEnable} from "../api/task.js";
import {ElMessageBox} from "element-plus";
import {isEmail} from "../util/email.js";
import {errorMsg, succesMsg} from "../util/box.js";

const userStore = useUserStore()

const ruleFormRef = ref()
const taskList = ref([])
const dialogVisible = ref(false)
const taskAdd = ref({
  userId: userStore.user.userId,
  taskDescription: "",
  taskCron: "",
  acceptEmail: "",
  sendContent: "",
  isEnable: true,
  taskType: "1"
})
const ruleForm = ref({
  taskDescription: [
    { required: true, message: '请输入主题', trigger: 'blur' },
  ],
  taskCron: [
    { required: true, message: '请输入表达式', trigger: 'blur' },
  ],
  acceptEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
  ],
  sendContent: [
    { required: true, message: '请输入内容', trigger: 'blur' },
  ],
})

const list = () => {
  _list(userStore.user.userId).then(res => {
    taskList.value = res.data.taskList
    for (let i = 0; i < taskList.value.length; i++) {
      if (taskList.value[i].isEnable === 0) {
        taskList.value[i].isEnable = false
      } else {
        taskList.value[i].isEnable = true
      }
    }
  })
}

onMounted(() => {
  list()
})

const toggleStatus = (status, id) => {
  if ( status ) {
    enable(id)
  } else {
    unEnable(id)
  }
}

const remove = (id) => {
  ElMessageBox.confirm('确定删除这个定时任务吗?').then(() => {
    _remove(id).then(res => {
      if ( res.success ) {
        succesMsg("删除成功")
        list()
      }
    })
  })
}

const enable = (id) => {
  _enable(id).then(res => {
    if ( res.success ) {
      succesMsg("启用成功")
      list()
    }
  })
}

const unEnable = (id) => {
  _unEnable(id).then(res => {
    if ( res.success ) {
      succesMsg("停用成功")
      list()
    }
  })
}

const handleClose = () => {
  ElMessageBox.confirm('确定要关闭窗口吗?').then(() => {
    dialogVisible.value = false
  })
}

const add = () => {
  // if ( !isValidCron(taskAdd.value.taskCron) ) {
  //   errorMsg("Cron表达式错误!")
  //   return
  // }
  if ( !isEmail(taskAdd.value.acceptEmail) ) {
    errorMsg("邮箱错误")
    return
  }
  if ( taskAdd.value.isEnable ) {
    taskAdd.value.isEnable = 1
  } else {
    taskAdd.value.isEnable = 0
  }
  _add(taskAdd.value).then(res => {
    if ( res.success ) {
      succesMsg("添加成功")
      taskAdd.value = {
        userId: userStore.user.userId,
        taskDescription: "",
        taskCron: "",
        acceptEmail: "",
        sendContent: "",
        isEnable: true,
        taskType: "1"
      }
      list()
      dialogVisible.value = false
    }
  })
  // dialogVisible = false
}

const validateAdd = async (formEl) => {
  await formEl.validate((valid, _) => {
    if (valid) {
      add();
    }
  })
}

</script>

<template>
  <div class="alignment-container" style="margin-top: 2%;display: flex;justify-content: center;align-items: center;">
    <el-card class="box-card" style="width: 90%">
      <template #header>
        <div class="card-header">
          <span>{{ userStore.user.username }} &nbsp;的定时任务列表</span>
          <el-button @click="dialogVisible = true" class="button" style="color: blue;margin-left: 20px" text bg>
            添加一个任务
          </el-button>
        </div>
      </template>
      <div>
        <el-table :data="taskList">
          <el-table-column align="center" fixed prop="taskId" label="唯一标识" width="120px"/>
          <el-table-column align="center" prop="taskDescription" label="主题" width="240px"/>
          <el-table-column align="center" prop="taskCron" label="Cron表达式" width="120px"/>
          <el-table-column align="center" prop="acceptEmail" label="接收邮箱" width="180px"/>
          <el-table-column align="center" prop="sendContent" label="任务内容" width="500px"/>
          <el-table-column align="center" prop="taskType" label="任务类型">
            <template #default="scope">
              <div>
                <el-button type="primary" text bg v-if="scope.row.taskType === 1">循环性</el-button>
                <el-button type="success" text bg v-else>一次性</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="isEnable" label="是否启用">
            <template #default="scope">
              <div>
                <el-switch
                    v-model="scope.row.isEnable"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                    @change="toggleStatus(scope.row.isEnable, scope.row.taskId)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间" width="180px"/>
          <el-table-column align="center" fixed="right" label="操作" width="180px">
            <template #default="scope">
              <el-button @click="remove(scope.row.taskId)" text bg type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>

  <el-dialog
      v-model="dialogVisible"
      title="添加定时任务"
      width="50%"
      :before-close="handleClose"
      draggable
  >
    <el-form
        label-position="right"
        label-width="auto"
        ref="ruleFormRef"
        :rules="ruleForm"
        :model="taskAdd"
    >
      <el-form-item label="主题" prop="taskDescription">
        <el-input v-model="taskAdd.taskDescription" prop />
      </el-form-item>
      <el-form-item label="任务表达式" prop="taskCron">
        <el-input v-model="taskAdd.taskCron" />
      </el-form-item>
      <el-form-item label="接收邮箱" prop="acceptEmail">
        <el-input v-model="taskAdd.acceptEmail" />
      </el-form-item>
      <el-form-item label="任务内容" prop="sendContent">
        <el-input type="textarea" v-model="taskAdd.sendContent" />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-switch v-model="taskAdd.isEnable" />
      </el-form-item>
      <el-form-item label="任务类型">
        <el-radio-group v-model="taskAdd.taskType">
<!--          <el-radio value="0">一次性</el-radio>-->
          <el-radio value="1">循环性</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="validateAdd(ruleFormRef)">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>